package com.atmilan.quartz.sync.push.crmeb.service.impl;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.atmilan.quartz.model.entity.buyer.BuyerBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductDescription;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.IStoreProductDescriptionService;
import com.atmilan.quartz.service.IStoreProductLuxurySourceService;
import com.atmilan.quartz.service.IStoreProductSourceService;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerBrandService;
import com.atmilan.quartz.sync.push.crmeb.service.ICrmebService;
import com.atmilan.quartz.utils.ImageSearchUtils;
import com.atmilan.quartz.utils.OSSUtil;
import com.atmilan.quartz.utils.RestTemplateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * crmeb 商品同步
 * @author muyu.myw
 * @date 2020/9/17 17:15
 */
@Slf4j
@Service
public class CrmebServiceImpl implements ICrmebService {
    @Value("${crmeb.domain}")
    private String crmebApiDomain;
    @Autowired
    IBuyerBrandService buyerBrandService;
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    OSSUtil ossUtil;

    @Resource
    private IStoreProductSourceService storeProductService;
    @Resource
    private IStoreProductDescriptionService storeProductDescriptionService;
    @Resource
    private IStoreProductLuxurySourceService storeProductLuxuryService;

    @Override
    public void syncBrand() {
        List<BuyerBrand> brandList = buyerBrandService.list();
        if (CollectionUtils.isNotEmpty(brandList)) {
            log.warn("{} - {} -------- start push brandList {} ");
            String json = JSON.toJSONString(brandList);
            List<StoreBrand> storeBrands = JSON.parseArray(json, StoreBrand.class);

            importBrandList(storeBrands);
            log.warn("{} - {} push brandList: {} ret  =  {}", brandList);
        }
    }

    private void importBrandList(List<StoreBrand> brandList) {
        if (CollectionUtils.isNotEmpty(brandList)) {
            List<StoreBrand> oldBrandList = storeBrandService.list();
            Map<Integer, StoreBrand> oldMap = oldBrandList.stream().collect(Collectors.toMap(StoreBrand::getId, Function.identity(), (old, newData) -> newData));
            brandList.forEach(brand -> {
                if (oldMap.containsKey(brand.getId())) {
                    brand.setId(oldMap.get(brand.getId()).getId());
                    storeBrandService.updateById(brand);
                } else {
                    storeBrandService.save(brand);
                }
            });

        }
    }

    /**
     * 图像搜索服务
     */
    @Override
    public Boolean seachImageTask() {
        // 获取需要上传的品牌
        List<Integer> brandListIds = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getIsAdvice, true)
                .eq(StoreBrand :: getType, 1)
                ).stream().map(StoreBrand :: getId).collect(Collectors.toList());
        
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, 0);
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, 1);
        if(CollectionUtils.isNotEmpty(brandListIds)) {
            lambdaQueryWrapper.in(StoreProduct::getBrandId, brandListIds);
        }
        lambdaQueryWrapper.eq(StoreProduct::getIsTusou, false);
        int count = storeProductService.count(lambdaQueryWrapper);
        // 计算执行数量
        int pageNo = 1;
        int pageSize = 100;
        int maxPage = (count / pageSize) + 1;
        // 开始任务
        long millis = System.currentTimeMillis();
        while (pageNo <= maxPage) {
        	int productId = 0;
            try {
                PageHelper.startPage(pageNo, pageSize);
                List<StoreProduct> storeProducts = storeProductService.list(lambdaQueryWrapper);
                PageInfo<StoreProduct> pageInfo = PageInfo.of(storeProducts);
                List<StoreProduct> products = pageInfo.getList();
                for (StoreProduct product : products) {
                	productId = product.getId();
                	// 查询图片
                	StoreProductDescription storeProductDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                			.eq(StoreProductDescription :: getProductId, productId)
                			.last("LIMIT 1")
                			);
                	product.setImage(storeProductDescription.getImage());
                    byte[] bytes = restTemplateUtil.getBytes(product.getImage());
                    boolean status = ImageSearchUtils.addImage(product.getBarCode(), product.getStoreName(), bytes);
                    if (status) {
                        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate().eq(StoreProduct::getId, product.getId()).set(StoreProduct::getIsTusou, true));
                    }
                }
                log.info("--------------- 图搜上传, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
            } catch (Exception e) {
                e.printStackTrace();
                storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate().eq(StoreProduct::getId, productId).set(StoreProduct::getIsTusou, true));
            }
            pageNo++;
        }
        return true;
    }
    
    /**
     * Crmeb商品 - 更换OSS图片URL任务
     */
    @Override
    public Boolean ossImageTask() {
        LambdaQueryWrapper<StoreProductDescription> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(StoreProductDescription::getIsDel, 0);
//        lambdaQueryWrapper.eq(StoreProductDescription::getIsShow, 1);
        lambdaQueryWrapper.isNotNull(StoreProductDescription::getImage);
        lambdaQueryWrapper.last("AND (image not like 'https://italytao%' and image not like 'http://sha-oss-static%' and image not like 'https://res.cloudinary%' and image not like 'https://img.alicdn%') ORDER BY id ASC");
        int count = storeProductDescriptionService.count(lambdaQueryWrapper);
        // 计算执行数量
        int pageNo = 1;
        int pageSize = 100;
        int maxPage = (count / pageSize) + 1;
        // 开始任务
        long millis = System.currentTimeMillis();
        while (pageNo <= maxPage) {
            try {
                PageHelper.startPage(pageNo, pageSize);
                List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(lambdaQueryWrapper);
                PageInfo<StoreProductDescription> pageInfo = PageInfo.of(storeProductDescriptions);
                List<StoreProductDescription> descriptions = pageInfo.getList();
                for (StoreProductDescription description : descriptions) {
                    ossUtil.sliderImageOssURL(description);
                    log.info("--------------- OSS图片上传, 当前页数: {}, 商品id: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, description.getProductId(), maxPage, (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
                }
                log.info("--------------- OSS图片上传, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
            } catch (Exception e) {
                e.printStackTrace();
            }
            pageNo++;
        }
        return true;
    }

}
